<template>
  <a-modal
    @cancel="close"
    :title="`新增${form.insureAddList[0].insureKind == 0 ? '交强险' : '商业险'}`"
    width="75vw"
    :visible="visible"
    unmount-on-close
    body-class="insure-add-modal-body"
    body-style="max-height: calc(100vh - 160px);"
  >
    <div class="insure-add-content">
      <page-form :model="form" ref="formRef" layout="vertical">
        <!-- 交强险 -->
        <compulsory-item
          v-if="form.insureAddList[0].insureKind == 0"
          :info="form.insureAddList[0]"
          operateType="addInsure"
          :fieldPrefix="`insureAddList.0.`"
          popupContainer=".insure-add-modal-body"
        />
        <!-- 商业险 -->
        <business-item
          v-if="form.insureAddList[0].insureKind == 1"
          :info="form.insureAddList[0]"
          operateType="addInsure"
          :fieldPrefix="`insureAddList.0.`"
          popupContainer=".insure-add-modal-body"
        />
      </page-form>
    </div>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" :loading="okLoading" @click="saveFn">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup name="InsureAddModal">
  import { ref } from 'vue'
  import { isValid } from '@/utils'
  import compulsoryItem from '@/views/assets/operation/car-insure/components/insurance-policy/compulsory-item.vue'
  import businessItem from '@/views/assets/operation/car-insure/components/insurance-policy/business-item.vue'
  import { insertInsure } from '@/api/asset/carInsure.js'
  import { Message, Modal } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  import { cloneDeep } from 'lodash-es'
  // emit 事件
  const emit = defineEmits(['ok'])
  const visible = ref(false)
  // 修改
  const form = ref({
    insureAddList: [{}],
  })

  // 车辆信息
  const carInfo = ref({})
  /**
   * 新增保险弹窗开启
   * @param info 车辆信息 { carId, licenseNo, siteId, siteName, compulsoryEndDate, businessEndDate }
   * @param insureKind 保险类型 0 交强险 1 商业险
   */
  const open = (info, insureKind) => {
    visible.value = true
    carInfo.value = info
    form.value = {
      carId: info.carId,
      licenseNo: info.licenseNo,
      insureAddList: [
        {
          siteId: info.siteId,
          siteName: info.siteName,
          insureKind: insureKind,
        },
      ],
    }
    // 商业险
    if (insureKind == 1) {
      form.value.insureAddList[0].carInsureDetail = [{}]
    }
  }
  // 关闭
  const close = () => {
    visible.value = false
    okLoading.value = false
    form.value = {
      insureAddList: [{}],
    }
  }
  // 校验保险结束日期是否大于开始日期
  const checkEndDate = () => {
    return new Promise((resolve) => {
      // 保单信息
      const insureInfo = form.value.insureAddList[0]
      const { endDate, insureKind } = insureInfo
      // 车辆的保单到期日
      const { compulsoryEndDate, businessEndDate } = carInfo.value
      // 交强险
      if (insureKind == 0) {
        if (compulsoryEndDate && dayjs(endDate).isBefore(compulsoryEndDate)) {
          Modal.confirm({
            title: '提示',
            okText: '确认',
            content: '当前交强险保单的到期日早于车辆上的交强险到期日，请确认是否新增？',
            onOk: () => {
              resolve()
            },
          })
        } else {
          resolve()
        }
      }
      // 商业险
      if (insureKind == 1) {
        if (businessEndDate && dayjs(endDate).isBefore(businessEndDate)) {
          Modal.confirm({
            title: '提示',
            okText: '确认',
            content: '当前商业险保单的到期日早于车辆上的商业险到期日，请确认是否新增？',
            onOk: () => {
              resolve()
            },
          })
        } else {
          resolve()
        }
      }
    })
  }
  // 保存
  const formRef = ref()
  const okLoading = ref(false)
  const saveFn = () => {
    formRef.value.validate(async (error) => {
      if (!error) {
        const param = {
          carId: form.value.carId,
          licenseNo: form.value.licenseNo,
        }
        const insureAddList = cloneDeep(form.value.insureAddList)
        insureAddList.forEach((insure) => {
          // 删除为空的投保信息（商业险）
          if (insure.insureKind == 1) {
            let carInsureDetail = cloneDeep(insure.carInsureDetail)
            if (carInsureDetail?.length > 0) {
              for (var i = 0; i < carInsureDetail.length; i++) {
                let item = carInsureDetail[i]
                let { insureKindType, insuredSum, insureAmt } = item
                if (!isValid(insureKindType) && !isValid(insuredSum) && !isValid(insureAmt)) {
                  carInsureDetail.splice(i, 1)
                  i--
                }
              }
            }
            insure.carInsureDetail = carInsureDetail
          }
        })
        param.insureAddList = insureAddList
        // 校验提示
        checkEndDate().then(() => {
          okLoading.value = true
          insertInsure(param)
            .then(() => {
              close()
              Message.success('保存成功')
              // 保存成功向上派发 ok 事件
              emit('ok', param)
            })
            .finally(() => {
              okLoading.value = false
            })
        })
      }
    })
  }
  defineExpose({
    open,
  })
</script>
<style lang="less" scoped>
  .insure-add-content {
    overflow-x: hidden;
  }
</style>
